<?php
if (! function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     *
     * @param  string  $url  资源相对地址
     * @param  bool  $domain  是否显示域名 或者直接传入域名
     *
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdn_url = "https://dkyx-1251560393.cos.ap-chengdu.myqcloud.com";
        $url = preg_match($regex, $url) ? $url : $cdn_url.$url;
        if ($domain && ! preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain.$url;
        }
        // 判断是否是图片
        if (preg_match("/(.*)\.(jpg|jpeg|png|gif|bmp)$/i", $url)) {
            $url .= "?imageMogr2/format/webp";
        }
        return $url;
    }
}


// 人性化时间
if (!function_exists('human_time')) {
    function human_time($time)
    {
        $time = (int) $time;
        $rtime = date("Y-m-d H:i", $time);
        $htime = date("H:i", $time);
        $time = time() - $time;
        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
//            $str = $h . '小时前 ' . $htime;
            $str = '今天 ' . $htime;
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor($time / (60 * 60 * 24));
            if ($d == 1) {
                $str = '昨天 ' . $rtime;
            } else {
                $str = '前天 ' . $rtime;
            }
        } else {
            $str = $rtime;
        }
        return $str;
    }
}


function getClientIP() {
    $ip = '';

    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        // X-Forwarded-For可能包含多个IP，第一个是真实IP
        $ip = explode(',', $ip);
        $ip = trim($ip[0]);
    } elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // 验证IP格式
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}
